<template>
  <div class="index">
    <img src="@/assets/img/fake/top.jpg" alt="" class="topimg" />
    <!-- <Carousel
      v-model="value1"
      loop
      autoplay
      :autoplay-speed="5000"
      class="carouselwrap"
    >
      <CarouselItem v-for="item in noticelist" :key="item.id">
        <div class="demo-carousel">{{ item.content }}</div>
        <img src="@/assets/img/fake/top.jpg" alt="" />
      </CarouselItem>
    </Carousel> -->
    <div class="subtitle">
      <div class="workarea" @click="showmodal('modal')">
        <span>{{ workarea || "点击选择职场" }}</span>
        <div class="icon"></div>
      </div>
      <div class="inputwrap">
        <Input
          search
          placeholder="请输入要锁搜的办公用品"
          v-model="searchKey"
          @on-change="onchange"
        />
      </div>
    </div>
    <div class="tab">
      <Tabs v-model="categoryId">
        <TabPane
          :label="item.categroryName"
          :name="item.categoryId"
          v-for="item in catelist"
          :key="item.categoryId"
        ></TabPane>
      </Tabs>
    </div>
    <div class="searcitem">
      <div class="price item" @click="sortPrice">
        <span>价格</span>
        <div class="icon">
          <div class="up"></div>
          <div class="down"></div>
        </div>
      </div>
      <div class="sellenum item" @click="sortAmount">销量</div>
    </div>
    <div class="list">
      <div
        class="itemone"
        v-for="item in goodslist"
        :key="item.id"
        @click="getDetail(item)"
      >
        <img :src="item.url.split(',')[0]" alt="" />
        <div class="detail">
          <div class="title">{{ item.goodsName }}</div>
          <div class="subtitle">
            <div class="price">{{ item.price }}</div>
            <div class="sellnumb">月销量：{{ item.amount }}</div>
          </div>
          <div class="subtitle">
            <div class="sku">库存充足</div>
            <div class="btn" @click.stop="addbusket(item)">+</div>
          </div>
        </div>
      </div>
    </div>
    <Page
      @on-change="changePageSize"
      :total="totalCount"
      :current="pageNumber"
      :page-size="pageSize"
      v-if="totalCount > pageSize"
    />
    <Modal v-model="modal" width="420">
      <p slot="header" style="span-align: center">
        <span>您需要选择您的职场地点</span>
      </p>
      <div class="workareapop">
        <div class="title">
          <Select v-model="province" size="small" style="width: 100px">
            <Option
              v-for="item in provincelist"
              :value="item.id"
              :key="item.id"
              >{{ item.title }}</Option
            >
          </Select>
          <Select v-model="city" size="small" style="width: 100px">
            <Option v-for="item in citylist" :value="item.id" :key="item.id">{{
              item.title
            }}</Option>
          </Select>
        </div>
        <div class="workarealist">
          <div
            class="workitem"
            v-for="item in workarealist"
            :key="item.id"
            @click="defaultarea = item"
            :class="item.id == defaultarea.id ? 'active' : ''"
          >
            {{ item.name }}
          </div>
        </div>
      </div>
      <div slot="footer" class="footer">
        <Button type="default" size="small" @click="modal = false">取消</Button>
        <Button type="primary" size="small" @click="ensureArea('modal')"
          >确定</Button
        >
      </div>
    </Modal>
    <Modal v-model="modal1" width="500">
      <div class="title addbuskethandler" slot="header">
        <img
          class="img"
          :src="addBusketItem.url.split(',')[0]"
          v-if="addBusketItem.url"
        />
        <div class="name">{{ addBusketItem.goodsName }}</div>
      </div>
      <div class="addbusket">
        <addbusketDetail
          v-if="modal1"
          :showKeyMoney="false"
          :goodsId="addBusketItem.goodsId"
          :storeId="addBusketItem.storeId"
          @func="closeAddBusket"
        ></addbusketDetail>
      </div>
      <div slot="footer"></div>
    </Modal>
    <Modal v-model="modal2" width="500">
      <div class="workArea" slot="header">
        <div class="name" style="text-align: center">
          总计：￥{{ carPrice }}
        </div>
        <div class="title">
          <div style="width: 100%">
            <div class="subtitle">
              <div>商品列表</div>
              <div class="clearCart" @click="clearCart">
                <span class="deleteicon"></span>
                清空购物车
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="workArea" v-if="modal2">
        <div class="goodslist">
          <div v-for="(item, index) in selectGoods" class="item" :key="index">
            <div class="name">{{ item.goodsName }}</div>
            <div class="sub">
              <span class="desc">{{ item.choseGuige.title }}</span>
              <span class="desc">剩余:{{ item.choseGuige.num }}</span>
              <span class="price">￥{{ item.choseGuige.price }}</span>
              <div class="count">
                <uni-number-box
                  :min="parseInt(item.choseGuige.beginCount)"
                  :value="parseInt(item.goodsNumber)"
                  :max="parseInt(item.choseGuige.num)"
                  :step="parseInt(item.choseGuige.beginCount)"
                  @change="monitorNumber($event, item, index)"
                ></uni-number-box>
              </div>
            </div>
          </div>
          <div
            v-if="selectGoods.length == 0"
            style="color: #ccc; span-align: center; padding: 30px"
          >
            空空如也
          </div>
        </div>
      </div>
    </Modal>
    <div class="bottom">
      <div class="left"></div>
      <div class="right">
        <div>
          总计：<span class="money" @click="modal2 = true"
            >￥{{ carPrice }}</span
          >
        </div>
        <div style="display: flex">
          <div class="keyMoney">
            个人余额：￥{{ accountBalance }}
            <div class="instro"></div>
          </div>
          <div v-if="carPrice != 0" class="btnwrap" @click="buyHandler">
            <div class="btn">领取</div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import uniNumberBox from "@/components/numbox";
import addbusketDetail from "@/components/addbusketdetail";
import { mapActions, mapMutations, mapState } from "vuex";
export default {
  data() {
    return {
      pageNumber: 1,
      pageSize: 12,
      modal: false,
      modal2: false,
      workarea: "点击选择职场",
      searchKey: "",
      value1: 0,
      noticelist: [],
      provincelist: [],
      province: null,
      citylist: [],
      city: null,
      workarealist: [],
      workarea: null,
      defaultarea: {},
      catelist: [],
      categoryId: "-1",
      sortParam: {
        name: "createTime",
        order: "desc",
      },
      busket: [], //领用篮
      selectGoods: [], //领用篮中选中的商品
      cartGoodsList: [],
      sortFlag: true,
      goodslist: [],
      totalCount: 0,
      carPrice: 0,
      addBusketItem: {},
      modal1: false,
    };
  },
  components: { addbusketDetail, uniNumberBox },
  computed: {
    ...mapState({
      workarea0: (state) => state.workarea,
      userInfo: (state) => state.userInfo,
      busket0: (state) => state.busket,
      accountBalance: (state) => state.accountBalance,
      departBalance: (state) => state.departBalance,
    }),
  },
  watch: {
    categoryId(val) {
      this.pageNumber = 1;
      this.getGoodsList();
    },
    province: {
      handler: function (val) {
        console.log("provicen", val);
        this.loadCities();
      },
      deep: true,
    },
    city: {
      handler: function (val) {
        this.loadAreas();
      },
      deep: true,
    },
    workarea(val) {
      this.updateWorkArea(val);
      this.getGoodsCategory();
    },
    busket0: {
      handler: function (val) {
        this.busket = val
      },
      deep: true,
    },
    busket: {
      handler: function (val) {
        this.initCarPrice();
      },
      deep: true,
    },
  },
  mounted() {
    this.busket = this.busket0;
    this.workarea = this.workarea0;
    this.getNotice();
    this.loadProvinces();
  },
  methods: {
    ...mapMutations(["updateWorkArea", "updateBusket"]),
    closeAddBusket(){
      console.log("关闭添加")
      this.modal1 = false
    },
    monitorNumber(e, item,index) {
      console.log(item)
      this.busket = this.busket.map((item0) => {
        if (item0.choseGuige.id == item.choseGuige.id) {
          item0.goodsNumber = e;
        }
        return item;
      });
    },
    clearCart() {
      let unchose = [];
      this.selectGoods = []
      this.busket.forEach((item) => {
        if (!item.selected) {
          unchose.push(item);
        }
      });
      this.updateBusket(unchose);
    },
    getDetail(item) {
      this.$router.push({
        path:"goodsdetail",
        query:{
          goodsId:item.goodsId,
          storeId:item.storeId
        }
      })
    },
    addbusket(item) {
      this.addBusketItem = item;
      this.$nextTick(() => {
        this.modal1 = true;
      });
    },
    changePageSize(e) {
      console.log(e);
      this.pageNumber = e;
      this.getGoodsList();
    },
    sortPrice() {
      this.sortFlag = !this.sortFlag;
      this.sortParam = { name: "price", order: "desc" };
      this.getGoodsList();
    },

    sortAmount() {
      this.sortFlag = !this.sortFlag;
      this.sortParam = { name: "amount", order: "desc" };
      this.getGoodsList();
    },
    onchange() {
      this.pageNumber = 1;
      this.getGoodsList();
    },
    getGoodsList() {
      this.axios
        .request({
          url: "/api/app/v1/goods/getGoodsList",
          params: {
            cateId: this.categoryId == "-1" ? "" : this.categoryId,
            storeId: this.defaultarea.id,
            goodsName: this.searchKey,
            pageSize: this.pageSize,
            isSale: 1,
            pageNumber: this.pageNumber,
            sort: this.sortParam.name,
            order: this.sortParam.order,
          },
          method: "get",
        })
        .then((res) => {
          if (res.success) {
            this.totalCount = res.result.totalPages;
            if (res.result.content) {
              this.goodslist = res.result.content;
            } else {
              this.goodslist = [];
            }
          }
        });
    },
    getGoodsCategory() {
      this.axios
        .request({
          url: "/api/app/v1/goods/getGoodsCategory",
          params: { address: this.workarea },
          method: "get",
        })
        .then((res) => {
          if (res.success) {
            this.catelist = [
              { categroryName: "全部用品", categoryId: "-1" },
              ...res.result,
            ];
            this.pageNumber = 1;
            this.getGoodsList();
          }
        });
    },
    buyHandler() {
      //status 表示购买结果0:正常，1：超出部门限额2：正常余额不足3：库存不足
      if (this.carPrice > this.accountBalance) {
        this.$Message.warning("余额不足,无法领取");
        return;
      } else {
        if (this.carPrice > this.departBalance) {
          this.$Message.warning("部门余额不足,无法领取");
          return;
        }
      }
      this.createOreder();
    },

    createOreder() {
      //提交购物车中选中的商品，仅剩下未选中的
      let unchoseGoods = [];
      let orderInfo = [];
      this.busket.forEach((obj) => {
        if (obj.selected) {
          orderInfo.push({
            skuId: obj.choseGuige.id,
            goodsId: obj.choseGuige.goodsId,
            num: obj.goodsNumber,
            price: obj.choseGuige.price,
            goodsName: obj.goodsName,
            storeId: obj.storeId,
            totalPrice: this.carPrice,
          });
        } else {
          unchoseGoods.push(obj);
        }
      });
      this.axios
        .request({
          url: "/api/app/v1/order/createOrder",
          data: JSON.stringify(orderInfo),
          method: "post",
        })
        .then((res) => {
          if (res.success) {
            this.updateBusket(unchoseGoods);
            this.$Message.success(res.result);
          } else {
            this.$Message.warning(res.message);
          }
        });
    },
    initCarPrice() {
      console.log("计算总计",this.busket)
      let totalPrice = 0;
      let arr = [];
      this.busket.forEach((item) => {
        if (item.selected) {
          totalPrice += item.choseGuige.price * item.goodsNumber;
          arr.push(item);
        }
      });
      this.$nextTick(()=>{
         this.selectGoods = arr;
         this.carPrice = totalPrice.toFixed(2);
      })
      
    },
    showmodal(name) {
      this[name] = true;
    },
    getNotice() {
      this.axios
        .request({
          url: `api/app/v1/goods/getFeedBack`,
          method: "get",
          params: {
            pageSize: 20,
            pageNumber: 1,
          },
        })
        .then((res) => {
          this.noticelist = res.result.content;
        });
    },
    ensureArea(name) {
      this.workarea = this.defaultarea.name;
      this[name] = false;
    },
    loadProvinces() {
      // 加载省份
      this.axios
        .request({
          url: "api/app/v1/goods/getFirstRegion",
          method: "get",
        })
        .then((res) => {
          this.provincelist = res.result;
        });
    },
    loadCities() {
      //加载市
      console.log("this.province", this.province);
      this.axios
        .request({
          url: "/api/app/v1/goods/getSecondRegion",
          params: { pageSize: 20, pageNumber: 1, parentId: this.province },
          method: "get",
        })
        .then((res) => {
          this.citylist = res.result;
        });
    },
    loadAreas() {
      //加载区域
      this.axios
        .request({
          url: "/api/app/v1/goods/getWareHouse",
          params: { regionId: this.city },
          method: "get",
        })
        .then((res) => {
          this.workarealist = res.result;
        });
    },
  },
};
</script>
<style lang="less" scoped>
@import "~@/assets/css/public.less";
.index {
  width: 100%;
  box-sizing: border-box;

  .subtitle {
    display: flex;
    justify-content: space-between;
    font-size: 14px;
    margin-top: 30px;
    .workarea {
      cursor: pointer;
      color: #2d8cf0;
      &:hover {
        color: #2d8cf0;
      }
    }
    .inputwrap {
      /deep/ .ivu-input {
        border-radius: 32px;
        font-size: 14px;
      }
    }
  }
  .searcitem {
    display: flex;
    width: 160px;
    align-items: center;
    border-bottom: 1upx solid #f8f8f8;
    justify-content: space-between;
    margin-bottom:15px;
    padding-left:15px;
    .item {
      text-align: center;
      cursor: pointer;
      &:active {
        color: #2d8cf0;
      }
      &.price {
        display: flex;
        justify-content: center;
        align-items: center;
        .icon {
          margin-left: 6px;
          .up {
            width: 0;
            border: 6px solid transparent;
            border-bottom-color: #d8d8d8;
            margin-bottom: 3px;
          }
          .down {
            width: 0;
            border: 6px solid transparent;
            border-top-color: #d8d8d8;
          }
        }
      }
    }
  }
  .list {
    display: flex;
    flex-wrap: wrap;
    .itemone {
      margin-right: 24px;
      text-align: left;
      background: #f7faff;
      border-radius: 0 0 8px 8px;
      width: 180px;
      img {
        width: 180px;
        height: 180px;
        border: 1px solid transparent;
      }
      .detail {
        padding: 10px;
        width: 100%;
        .title {
          font-weight: bold;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
          width: 100%;
        }
        .subtitle {
          margin-top: 3px;
          display: flex;
          align-items: center;
          font-size: 11px;
          color: #666666;
          .btn {
            background: #2d8cf0;
            color: #fff;
            font-weight: bold;
            width: 45px;
            height: 18px;
            text-align: center;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 16px;
            border-radius: 4px;
            cursor: pointer;
          }
        }
      }
    }
  }
  .bottom {
    z-index: 1000;
    position: fixed;
    bottom: 0;
    width: 100%;
    left: 0;
    display: flex;
    justify-content: space-between;
    align-items: center;
    box-sizing: border-box;
    font-size: 26upx;
    color: #333;

    height: 70px;

    .left {
      width: 180px;
    }
    .right {
      border-top: 1px solid #e3e3e3;
      height: 100%;
      flex: 1;
      padding: 0 50px;
      background: #fff;
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
    .money {
      font-size: 18px;
      color: #ff4117;
      font-weight: bold;
    }
    .keyMoney {
      margin-left: 5px;
      display: flex;
      align-items: center;
    }
    .instro {
      margin-left: 5px;
      width: 14px;
      height: 14px;
      .bg-image("~@/assets/img/说明");
    }
    .btnwrap {
      margin-left: 30px;
      .btn {
        float: right;
        width: 100px;
        height: 32px;
        display: flex;
        justify-content: center;
        align-items: center;
        background: #ff4117;
        border-radius: 32px;
        color: #fff;
      }
    }
  }
  .topimg {
    width: 100%;
  }

  .carouselwrap {
    /deep/.ivu-carousel-item {
      position: relative;

      .demo-carousel {
        position: absolute;
        left: 50%;
        bottom: 10px;
        transform: translateX(-50%);
      }
    }
  }
}
.addbuskethandler {
  display: flex;
  align-items: center;
  .img {
    height: 60px;
    width: 60px;
  }
  .name {
    margin-left: 20px;
    color: #333;
  }
}
.workareapop {
  .title {
    text-align: center;
  }
  .workarealist {
    height: 300px;
    overflow-y: auto;
    margin-top: 15px;
    border-top: 1px solid #eee;
    .workitem {
      cursor: pointer;
      height: 40px;
      line-height: 40px;
      border-bottom: 1px solid #eee;
      padding: 0 15px;
      &.active {
        color: #2d8cf0;
        background: #f0faff;
      }
    }
  }
}
.workArea {
  .title {
    padding:0 15px;
    text-align: center;
    font-weight: bold;
   
    font-size: 15px;
    display: flex;
    justify-content: space-between;
    .close {
      font-weight: normal;
      color: #666;
    }
    .ensure {
      font-weight: normal;
      color: #007aff;
    }
    .subtitle {
      display: flex;
      justify-content: space-between;
      color: #666;
      font-size: 13px;
      margin-top:30px;
      .clearCart {
        display: flex;
        align-items: center;
        .deleteicon {
          width: 12px;
          height: 15px;
          margin-right: 5px;
          .bg-image("~@/assets/img/清空");
        }
      }
    }
  }
  .pick {
    height: 250px;
  }
  .goodslist {
    height: 400px;
    overflow-x: hidden;
    overflow-y: auto;
    
    .item {
      padding: 10px;
      border-bottom:1px solid #f0f0f0;
      .name {
        white-space: nowrap;
        width: 100%;
        overflow: hidden;
        text-overflow: ellipsis;
        font-weight: bold;
        color: #333;
      }
      .sub {
        display: flex;
        justify-content: space-between;
        align-items: center;
        .desc {
          color: #999;
          padding-right: 10px;
          border-right: 1px solid #999;
          margin-right: 10px;
        }
        .num {
          font-size: 14px;
          color: #ff4117;
          font-weight: bold;
          text-align: left;
          flex: 1;
        }
        .price {
          font-size: 14px;
          color: #ff4117;
          font-weight: bold;
          text-align: left;
          flex: 1;
        }
      }
    }
  }
}
</style>